﻿using System;
using System.Windows;
using System.Windows.Media;
using System.ComponentModel;
using System.Drawing;
using System.Collections.Generic;
using NLog;

namespace NGImgGetter
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public string savePath = string.Empty;
        BackgroundWorker bw = new BackgroundWorker();
        private static Logger logger = LogManager.GetCurrentClassLogger();

        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrEmpty(Properties.Settings.Default.LatestSavePath))
                txtSavePath.Text = savePath = Properties.Settings.Default.LatestSavePath;

            CreateBackgroundWorker();
        }

        private void txtSavePath_GotFocus(object sender, RoutedEventArgs e)
        {
            var dialog = new System.Windows.Forms.FolderBrowserDialog();
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                txtSavePath.Text = savePath = dialog.SelectedPath;
        }

        private void CreateBackgroundWorker()
        {
            bw.WorkerSupportsCancellation = bw.WorkerReportsProgress = true;
            bw.ProgressChanged += (s, a) =>
                {
                    pbLoad.Value = a.ProgressPercentage;
                };
            bw.DoWork += (s, a) =>
            {
                //try
                //{
                //    ((BackgroundWorker)s).ReportProgress(5);
                //    System.Drawing.Image img = ImageGrabberAPI.ImageGrabber.GetImageByMarkDeep("http://photography.nationalgeographic.com/photography/photo-of-the-day", null, "photo-of-the-day", "http://photography.nationalgeographic.com", "jpg", 1, 0);
                //    ((BackgroundWorker)s).ReportProgress(60);
                //    if (img.Tag != null)
                //    {
                //        string filename = savePath + "\\" + img.Tag;
                //        img.Save(filename);
                //        a.Result = filename;
                //        ((BackgroundWorker)s).ReportProgress(70);
                //        Properties.Settings.Default.LatestSavePath = savePath;
                //        Properties.Settings.Default.Save();
                //    }
                //}
                //catch (Exception ex)
                //{
                //    a.Cancel = true;
                //    a.Result = ex.Message;
                //}
                List<Image> imgList = new List<Image>();
                for (int i = 0; i < 1; i++)
                {
                    imgList.Add(ImageGrabberAPI.ImageGrabber.GetImageByMarkDeep("http://photography.nationalgeographic.com/photography/photo-of-the-day", "photo-of-the-day", "jpg", 2));
                }

                for (int i = 0; i < imgList.Count; i++)
                {
                    string filename = savePath + "\\" + imgList[i].Tag;
                    (imgList[i]).Save(filename);
                    ((BackgroundWorker)s).ReportProgress(i * 100 / imgList.Count);
                    Properties.Settings.Default.LatestSavePath = savePath;
                    Properties.Settings.Default.Save();
                }

            };

            bw.RunWorkerCompleted += (s, a) =>
            {
                try
                {
                    if (a.Cancelled)
                    {
                        ShowErrorResult(a.Result.ToString());
                        pbLoad.Value = 0;
                    }
                    else
                    {
                        if (a.Result != null)
                            ShowSuccessResult(a.Result.ToString());
                        pbLoad.Value = 100;
                    }
                }
                catch (Exception ex)
                {
                    logger.ErrorException("CreateBackgroundWorker", ex);
                }
            };
        }
        private void btnSaveImageOfTheDay_Click(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(savePath) && savePath.Contains(":"))
            {
                if (!bw.IsBusy)
                    bw.RunWorkerAsync(int.Parse(txtCount.Text));
            }
        }

        private void ShowErrorResult(string detailedError)
        {
            lblResult.Content = "Error! " + detailedError;
            lblResult.Foreground = new SolidColorBrush(Colors.Red);
        }

        private void ShowSuccessResult(string savedFilename)
        {
            lblResult.Content = "Success! Saved as " + savedFilename;
            lblResult.Foreground = new SolidColorBrush(Colors.Green);
        }

        private void lblResult_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (!string.IsNullOrEmpty(Properties.Settings.Default.LatestSavePath))
                System.Diagnostics.Process.Start(Properties.Settings.Default.LatestSavePath);
        }
    }
}
